package me.zhengjie.modules.finace_taxation.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.AllArgsConstructor;
import me.zhengjie.base.PageInfo;
import me.zhengjie.base.QueryHelpMybatisPlus;
import me.zhengjie.modules.finace_taxation.domain.FtOrderSchedule;
import me.zhengjie.modules.finace_taxation.domain.FtOrderVO;
import me.zhengjie.modules.finace_taxation.domain.FtServiceVO;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.system.service.mapper.DictDetailMapper;
import me.zhengjie.modules.system.service.mapper.DictMapper;
import me.zhengjie.utils.ConvertUtil;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.modules.finace_taxation.domain.FtOrder;
import me.zhengjie.modules.finace_taxation.service.FtOrderService;
import me.zhengjie.modules.finace_taxation.service.dto.FtOrderDto;
import me.zhengjie.modules.finace_taxation.service.dto.FtOrderQueryParam;
import me.zhengjie.modules.finace_taxation.service.mapper.FtOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @author 杨荣森
* @date 2021-06-30
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = FtOrderService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class FtOrderServiceImpl implements FtOrderService {

    // private final RedisUtils redisUtils;
    private final FtOrderMapper ftOrderMapper;

    @Autowired
    private DictDetailMapper dictDetailMapper;

    @Override
    public PageInfo<FtOrderDto> queryAll(Map<String,Object> map, Pageable pageable) {
        IPage<FtOrderDto> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<FtOrderDto> page = ftOrderMapper.getOrders(queryPage, map);
        List<DictDetailDto> dictDetails = dictDetailMapper.getDictDetailsByDictName("schedule");
        for (int i = 0;i<page.getRecords().size();i++){
            FtOrderSchedule ftOrderSchedule = ftOrderMapper.getOrderScheduleByOrderId(page.getRecords().get(i).getId());
            page.getRecords().get(i).setUpdateTime(ftOrderSchedule.getUpdateTime());
            page.getRecords().get(i).setSchedule(ftOrderSchedule.getSchedule());
            for (int j = 0;j<dictDetails.size();j++){
                if(dictDetails.get(j).getLabel().equals(page.getRecords().get(i).getSchedule())){
                    page.getRecords().get(i).setSchedule(dictDetails.get(j).getValue());
                }
            }
        }
        return ConvertUtil.convertPage(page, FtOrderDto.class);
    }

    @Override
    public List<FtOrderDto> queryAll(FtOrderQueryParam query){
        return ConvertUtil.convertList(ftOrderMapper.getOrdersDownLoad(query), FtOrderDto.class);
    }

    @Override
    public FtOrder getById(String id) {
        return ftOrderMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public FtOrderDto findById(String id) {
        return ConvertUtil.convert(getById(id), FtOrderDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(FtOrderDto resources) {
        FtOrder entity = ConvertUtil.convert(resources, FtOrder.class);
        return ftOrderMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(FtOrderDto resources){
        FtOrder entity = ConvertUtil.convert(resources, FtOrder.class);
        int ret = ftOrderMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<String> ids){
        // delCaches(ids);
        return ftOrderMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateOrderSchedule(FtOrderSchedule ftOrderSchedule) {
        return ftOrderMapper.updateOrderSchedule(ftOrderSchedule);
    }

    @Override
    public List<FtOrderVO> getOrdersByUserId(Map<String, Object> map) {
        int pageNo = Integer.parseInt(map.get("pageNo").toString());
        int pageSize = Integer.parseInt(map.get("pageSize").toString());
        Page<FtServiceVO> queryPage = new Page<>(pageNo,pageSize);
        List<FtOrderVO> ftOrderDtos = ftOrderMapper.getOrdersByUserId(queryPage, map);
        List<DictDetailDto> dictDetails = dictDetailMapper.getDictDetailsByDictName("schedule");
        String[] coverImgs = null;
        for (int i = 0;i<ftOrderDtos.size();i++){
            coverImgs = ftOrderDtos.get(i).getCoverImg().split(",");
            ftOrderDtos.get(i).setCoverImg(coverImgs[0]);
            FtOrderSchedule ftOrderSchedule = ftOrderMapper.getOrderScheduleByOrderId(ftOrderDtos.get(i).getId());
            ftOrderDtos.get(i).setUpdateTime(ftOrderSchedule.getUpdateTime());
            ftOrderDtos.get(i).setSchedule(ftOrderSchedule.getSchedule());
            for (int j = 0;j<dictDetails.size();j++){
                if(dictDetails.get(j).getLabel().equals(ftOrderDtos.get(i).getSchedule())){
                    ftOrderDtos.get(i).setSchedule(dictDetails.get(j).getValue());
                }
            }
        }
        return ftOrderDtos;
    }

    @Override
    public List<FtOrderSchedule> getOrderScheduls(String orderId) {
        return ftOrderMapper.getOrderScheduls(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(String id){
        Set<String> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(String id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<String> ids) {
        for (String id: ids) {
            delCaches(id);
        }
    }*/

    @Override
    public void download(List<FtOrderDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
        List<DictDetailDto> dictDetails = dictDetailMapper.getDictDetailsByDictName("schedule");
      for (int i = 0;i<all.size();i++){
          FtOrderSchedule ftOrderSchedule = ftOrderMapper.getOrderScheduleByOrderId(all.get(i).getId());
          all.get(i).setUpdateTime(ftOrderSchedule.getUpdateTime());
          all.get(i).setSchedule(ftOrderSchedule.getSchedule());
          for (int j = 0;j<dictDetails.size();j++){
              if(dictDetails.get(j).getLabel().equals(all.get(i).getSchedule())){
                  all.get(i).setSchedule(dictDetails.get(j).getValue());
              }
          }
      }
      for (FtOrderDto ftOrder : all) {
        Map<String,Object> map = new LinkedHashMap<>();
          map.put("客户姓名", ftOrder.getUserName());
          map.put("联系方式", ftOrder.getContactNumber());
          map.put("所属服务", ftOrder.getServiceTitle());
          map.put("订单类型", ftOrder.getType());
          map.put("订单时间", ftOrder.getOrderTime());
          map.put("进度", ftOrder.getSchedule());
          map.put("进度修改时间", ftOrder.getUpdateTime());
          map.put("咨询内容", ftOrder.getContent());
          map.put("备注", ftOrder.getRemark());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }
}
